package com.example.li_han.servlet;

import com.example.li_han.pojo.NewsType;
import com.example.li_han.service.NewsTypeService;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取所有分类Servlet
 */
@WebServlet(name = "GetAllNewsTypes", value = "/GetAllNewsTypes")
public class GetAllNewsTypes extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");

        Map<String, Object> resultMap = new HashMap<>();

        try {
            NewsTypeService newsTypeService = new NewsTypeService();
            List<NewsType> typeList = newsTypeService.getAllNewsTypes();

            if (typeList != null && !typeList.isEmpty()) {
                resultMap.put("code", 200);
                resultMap.put("msg", "获取成功");
                resultMap.put("data", typeList);
                resultMap.put("count", typeList.size());
            } else {
                resultMap.put("code", 200);
                resultMap.put("msg", "暂无分类数据");
                resultMap.put("data", new java.util.ArrayList<>());
                resultMap.put("count", 0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "获取失败: " + e.getMessage());
            resultMap.put("data", new java.util.ArrayList<>());
            resultMap.put("count", 0);
        }

        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }
}